package co.yixiang.modules.mp.serviceimpl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.ObjectUtil;
import co.yixiang.common.service.impl.BaseServiceImpl;
import co.yixiang.common.utils.FileUtil;
import co.yixiang.common.utils.QueryHelpPlus;
import co.yixiang.dozer.service.IGenerator;
import co.yixiang.modules.mp.entity.domain.YxArticle;
import co.yixiang.modules.mp.entity.domain.YxArticleVisitLog;
import co.yixiang.modules.mp.entity.dto.YxArticleCategoryDto;
import co.yixiang.modules.mp.entity.dto.YxArticleVisitLogDto;
import co.yixiang.modules.mp.entity.dto.YxArticleVisitLogQueryCriteria;
import co.yixiang.modules.mp.mapper.ArticleVisitLogMapper;
import co.yixiang.modules.mp.service.YxArticleService;
import co.yixiang.modules.mp.service.YxArticleVisitLogService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class YxArticleVisitLogServiceImpl extends BaseServiceImpl<ArticleVisitLogMapper, YxArticleVisitLog> implements YxArticleVisitLogService {
    @Autowired
    private YxArticleService articleService;

    private final IGenerator generator;

    public YxArticleVisitLogServiceImpl(IGenerator generator) {
        this.generator = generator;
    }


    @Override
    public Map<String, Object> queryAll(YxArticleVisitLogQueryCriteria criteria, Pageable pageable) {
        getPage(pageable);
        PageInfo<YxArticleVisitLog> page = new PageInfo<>(queryAll(criteria));
        Map<String, Object> map = new LinkedHashMap<>(2);
        map.put("content", generator.convert(page.getList(), YxArticleCategoryDto.class));
        map.put("totalElements", page.getTotal());
        return map;
    }

    @Override
    public List<YxArticleVisitLog> queryAll(YxArticleVisitLogQueryCriteria criteria) {
        return baseMapper.selectList(QueryHelpPlus.getPredicate(YxArticleVisitLog.class, criteria));
    }

    @Override
    public List<YxArticleVisitLog> queryAllByArticleId(Integer articleId) {
        return list(new LambdaQueryWrapper<YxArticleVisitLog>().eq(YxArticleVisitLog::getArticleId, articleId));
    }

    @Override
    public void download(List<YxArticleVisitLogDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (YxArticleVisitLogDto yxArticle : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("文章id", yxArticle.getArticleId());
            map.put("文章作者", yxArticle.getAuthor());
            map.put("文章标题", yxArticle.getTitle());
            map.put("原文连接", yxArticle.getUrl());
            map.put("用户id", yxArticle.getUid());
            map.put("浏览次数", yxArticle.getVisit());
            map.put("最大浏览时长/秒", yxArticle.getMaxTime());
            map.put("总浏览时长/秒", yxArticle.getTotalTime());
            map.put("点赞状态", yxArticle.getLikeStatus());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public void update(YxArticleVisitLog resources) {

    }

    @Override
    public Object create(YxArticleVisitLog resources) {
        return save(resources);
    }

    @Override
    public YxArticleVisitLog createOrUpdate(YxArticleVisitLog resources) {
        // 1.查询 用户是否已经浏览过对应的文章
        final YxArticleVisitLog one = this.getOne(new LambdaQueryWrapper<YxArticleVisitLog>().eq(YxArticleVisitLog::getArticleId,resources.getArticleId()).eq(YxArticleVisitLog::getUid,resources.getUid()));
        YxArticle article = articleService.getOne(new LambdaQueryWrapper<YxArticle>().eq(YxArticle::getId, resources.getArticleId()));
        //article.setVisit(article.getVisit() + 1);
        // 为空则添加浏览记录
        if (ObjectUtil.isEmpty(one)) {
            // 更新文章的点赞数量
            if (resources.getLikeStatus()) {
                // 文章点赞数增加+1
                article.setLike(article.getLike() + 1);
            }
            articleService.update(article);
            save(resources);
            return resources;
        }
        one.setVisit(one.getVisit()+1);
        one.setMaxTime(one.getMaxTime() > resources.getMaxTime() ? one.getMaxTime() : resources.getMaxTime());
        one.setTotalTime(one.getTotalTime() + resources.getMaxTime());
        one.setUpdateTime(DateTime.now());
        if (resources.getLikeStatus() && !one.getLikeStatus()) {
            article.setLike(article.getLike() + 1);
        } else if (!resources.getLikeStatus() && one.getLikeStatus()) {
            article.setLike(article.getLike() - 1);
        }
        one.setLikeStatus(resources.getLikeStatus());
        //articleService.update(article);
        updateById(one);
        return one;
    }
}
